<template>
  <q-dialog v-model="dialog" position="bottom">
    <div class="bg-white full-width" style="border-radius: 8px 8px 0px 0px">
      <div><q-btn padding="sm sm" @click="close" style="color: #999" unelevated round icon="close" /></div>

      <section class="q-pa-md">
        <div style="font-size: 20px; font-weight: bold">阅读并同意相关协议</div>
        <div class="q-mt-xs" style="color: #999; font-size: 12px">请仔细阅读并同意以下协议</div>
        <div v-if="!webUrl" style="word-break: break-all" class="q-mt-sm">
          特别提醒：尊敬的客户，为维护您的合法权益，请你仔细阅读本授权书条款，并特别注意其中以黑体标注的条款。除非您已阅读并接受本授权书所有条款，否则请不要进行后续操作。您通过网络页面或客户端同意本授权书，即视为您已经充分阅读并理解本授权书所有条款同意承担由此带来的一切法律后果。
        </div>
        <div v-else class="q-mt-sm">
          <iframe
            ref="iframeRef"
            :src="webUrl"
            class="relative-position"
            style="border: none; outline: none; height: 200px; width: 100%; z-index: 4"
          ></iframe>
          <div class="absolute-full center" style="z-index: 1" v-if="isShowIframeLoading">
            <q-spinner color="primary" size="3em" />
          </div>
        </div>

        <q-btn
          label="同意协议并授权"
          padding="none none"
          unelevated
          :loading="loading"
          rounded
          @click="() => (isAgainCheck ? submitAgainCheck() : submit())"
          class="full-width q-mt-xl"
          style="
            background-color: #ffd101;
            color: #000;
            padding: 8px 18px !important;
            font-size: 15px;
            font-weight: 600;
          "
        />
      </section>
    </div>
  </q-dialog>
</template>

<script setup lang="ts">
import { ref, watchEffect } from 'vue';
import SignatureDialog from './SignatureDialog.vue';
import { Show, ShowAgainCheck } from './Protocol';
import { useAppStore } from 'src/stores/app-store';
import { approveToPushApi } from 'src/api/info';
import { showLoadingToast } from 'vant';
import { useRoute, useRouter } from 'vue-router';
import { useMechanismStore } from 'src/stores/mechanism-store';
import { approveClickCountApi, pushToMerchantApi } from 'src/api/merchant';
import { MatchResultOrderItemList } from 'src/types/matchResult';
import { CheckUserRes } from '../prodList';

const router = useRouter();
const route = useRoute();

const webUrl = ref('');
const iframeRef = ref<HTMLIFrameElement>();
const isShowIframeLoading = ref(true);

const loading = ref(false);

watchEffect(() => {
  if (!iframeRef.value) return;
  iframeRef.value.onload = () => {
    isShowIframeLoading.value = false;
  };
});

const isAgainCheck = ref<boolean>(false);

const dialog = ref(false);
const param = ref<MatchResultOrderItemList>();
const show: Show = (_param) => {
  isAgainCheck.value = false;
  isShowIframeLoading.value = true;
  param.value = _param;
  if (_param.protocolUrl) {
    webUrl.value = _param.protocolUrl;
  }
  dialog.value = true;
};

const againCheck = ref<CheckUserRes>();
const showAgainCheck: ShowAgainCheck = (_param) => {
  isAgainCheck.value = true;
  isShowIframeLoading.value = true;
  againCheck.value = _param;
  if (_param.protocolUrl) {
    webUrl.value = _param.protocolUrl;
  }
  dialog.value = true;
};

const close = () => {
  dialog.value = false;
};
const submit = async () => {
  if (!param.value) return;

  loading.value = true;
  const toast = showLoadingToast({
    iconSize: 50,
    forbidClick: true,
    duration: 0,
  });

  const { orderId } = useMechanismStore();
  await approveClickCountApi({ orderNo: orderId, orderItemId: param.value.orderItemId }).finally(
    () => (loading.value = false),
  );
  toast.close();
  if (param.value.approveUrl) {
    window.location.href = param.value.approveUrl;
    return;
  }
  // SignatureDialogRef.value?.show(param.value)
};
const submitAgainCheck = async () => {
  if (!againCheck.value) return;


  loading.value = true;
  const toast = showLoadingToast({
    iconSize: 50,
    forbidClick: true,
    duration: 0,
  });

  await pushToMerchantApi({ orderNo: againCheck.value?.pushOrderNo }).finally(() => (loading.value = false));
  toast.close();
  router.replace({path: 'evaluateAuth', query: {...route.query, isToProdList: '1',}})
  // SignatureDialogRef.value?.show(param.value)
};
defineExpose({ show, showAgainCheck });
</script>
